<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/7/21
 * Time: 11:17
 */

namespace App\Services;

use App\Goods;
use App\GoodsFiles;
use App\GoodsInquirys;
use App\GoodsParams;
use App\GoodsSpecs;
use App\ServiceFiles;
use DB;
use App\GoodsCategory;
use App\Lib\Util\QueryPager;
use Maatwebsite\Excel\Facades\Excel;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
use PDF;

class GoodsService
{
    public function getGoods(Array $input, $paging = true)
    {
        $query = new Goods();

        if (!empty($input['goods_name'])) {
            $query = $query->where('goods_name', 'like', '%' . $input['goods_name'] . '%');
        }

        if (!empty($input['goods_vendor'])) {
            $query = $query->where('goods_vendor', 'like', '%' . $input['goods_vendor'] . '%');
        }

        if (!empty($input['list_flag'])) {
            $query = $query->where('list_flag', $input['list_flag']);
        }

        if (!empty($input['goods_category'])) {
            $service = new GoodsCategoryService();
            $list    = $service->getAllCate();
            $child   = $service->getAllChild($list, $input['goods_category']);
            $child[] = $input['goods_category'];
            $query   = $query->whereHas('goodsCategory', function ($query) use ($child) {
                $query->whereIn('goods_categories.id', $child);
            });
        }

        if (!empty($input['goods_score_min']) || !empty($input['goods_score_max'])) {
            if (!empty($input['goods_score_min']) && !empty($input['goods_score_max'])) {
                if ($input['goods_score_min'] > $input['goods_score_max']) {
                    $mid                      = $input['goods_score_max'];
                    $input['goods_score_max'] = $input['goods_score_min'];
                    $input['goods_score_min'] = $mid;
                }
            }
            $query = $query->whereBetween('goods_score', [$input['goods_score_min'] ?: Goods::$GOODS_SCORE_MIN, $input['goods_score_max'] ?: Goods::$GOODS_SCORE_MAX]);
        }

        $pager = new QueryPager($query);

        $pager->mapField('list_flag', Goods::$GOODS_LIST_FLAG_MAP);

        $pager->setRefectionMethodField('goodsCategoryGet');
        $pager->setRefectionMethodField('getFullPicturePath');
        $pager->setRefectionMethodField('getFile');

        return $paging ? $pager->doPaginate($input, 'sort_order') :
            $pager->queryWithoutPaginate($input, 'sort_order');
    }

    public function getIndexGoods()
    {
        $list = GoodsSpecs::orderBy('sort_order', 'asc')->orderBy('id', 'asc')->take(4)->get();
        return $list;
    }


    public function goodsAdd(Array $input)
    {
        DB::transaction(function () use ($input) {
            $goodsInfo = Goods::create([
                'goods_name'        => $input['goods_name'],
                'goods_vendor'      => $input['goods_vendor'],
                'sort_order'        => $input['sort_order'],
                'goods_category_id' => $input['goods_category_id'],
                'goods_picture'     => $input['goods_picture'],
                'list_flag'         => $input['list_flag'],
                'goods_content'     => $input['goods_content'],
            ]);
            $fileData  = [
                $input['goods_file_id'],
                $input['goods_file_id2'],
                $input['goods_file_id3'],
                $input['goods_file_id4'],
                $input['goods_file_id5'],
            ];
            foreach ($fileData as $v) {
                if (!empty($v)) {
                    GoodsFiles::create([
                        'file_id'  => $v,
                        'goods_id' => $goodsInfo->id
                    ]);
                }
            }
            $goodsInfo->goods_qrcode = $this->goodsQRCode($goodsInfo->id);
            $goodsInfo->save();
        });
    }

    public function goodsQRCode($goodsId)
    {
        if (!file_exists(storage_path('app/public/qrcodes'))) {
            mkdir(storage_path('app/public/qrcodes'));
        }
        $qrname = date('Y-m-d') . '-' . uniqid() . '.png';
        QrCode::format('png')->size(160)->generate(url('web/goods/detail', [$goodsId]), storage_path('app/public/qrcodes/' . $qrname));
        return $qrname;
    }

    public function goodsEdit(Array $input)
    {
        DB::transaction(function () use ($input) {
            Goods::where('id', $input['id'])->update([
                'goods_name'        => $input['goods_name'],
                'goods_vendor'      => $input['goods_vendor'],
                'sort_order'        => $input['sort_order'],
                'goods_category_id' => $input['goods_category_id'],
                'goods_picture'     => $input['goods_picture'],
                'list_flag'         => $input['list_flag'],
                'goods_content'     => $input['goods_content'],
            ]);
            $fileData = [
                $input['goods_file_id'],
                $input['goods_file_id2'],
                $input['goods_file_id3'],
                $input['goods_file_id4'],
                $input['goods_file_id5'],
            ];
            GoodsFiles::where('goods_id', $input['id'])->delete();
            foreach ($fileData as $v) {
                if (!empty($v)) {
                    GoodsFiles::create([
                        'file_id'  => $v,
                        'goods_id' => $input['id']
                    ]);
                }
            }
//            if (!empty($input['goods_file_id'])) {
//                $fileInfo = GoodsFiles::where('goods_id', $input['id'])->first();
//                if ($fileInfo) {
//                    GoodsFiles::where('goods_id', $input['id'])->update([
//                        'file_id' => $input['goods_file_id']
//                    ]);
//                } else {
//                    GoodsFiles::create([
//                        'file_id'  => $input['goods_file_id'],
//                        'goods_id' => $input['id']
//                    ]);
//                }
//            }
        });
    }

    public function goodsDel(Array $input)
    {
        DB::transaction(function () use ($input) {
            GoodsParams::where('goods_id', $input['id'])->delete();
            GoodsSpecs::where('goods_id', $input['id'])->delete();
            GoodsFiles::where('goods_id', $input['id'])->delete();
            Goods::where('id', $input['id'])->delete();
        });
    }

    public function delGoodsBatch(Array $input)
    {
        DB::transaction(function () use ($input) {
            GoodsParams::whereIn('goods_id', $input['ids'])->delete();
            GoodsSpecs::whereIn('goods_id', $input['ids'])->delete();
            GoodsFiles::whereIn('goods_id', $input['ids'])->delete();
            Goods::whereIn('id', $input['ids'])->delete();
        });
    }

    public function getGoodsInquirys(Array $input, $paging = true)
    {
        $query = new GoodsInquirys();

        if (!empty($input['goods_name'])) {
            $query = $query->whereHas('goods', function ($query) use ($input) {
                $query->where('goods.goods_name', 'like', '%' . $input['goods_name'] . '%');
            });
        }

        if (!empty($input['goods_vendor'])) {
            $query = $query->whereHas('goods', function ($query) use ($input) {
                $query->where('goods.goods_vendor', 'like', '%' . $input['goods_name'] . '%');
            });
        }

        if (!empty($input['display_flag'])) {
            $query = $query->where('display_flag', $input['display_flag']);
        }

        if (!empty($input['goods_category'])) {
            $service = new GoodsCategoryService();
            $list    = $service->getAllCate();
            $child   = $service->getAllChild($list, $input['goods_category']);
            $child[] = $input['goods_category'];
            $query   = $query->whereHas('goods', function ($query) use ($child) {
                $query->whereIn('goods.goods_category_id', $child);
            });
        }

        if (!empty($input['process_status'])) {
            $query = $query->where('process_status', $input['process_status']);
        }
        $pager = new QueryPager($query);

        $pager->mapField('display_flag', GoodsInquirys::$DISPLAY_FLAG_MAP);

        $pager->setRefectionMethodField('goodsGet');
        $pager->setRefectionMethodField('goodsCategoryGet');
        $pager->setRefectionMethodField('usersGet');

        return $paging ? $pager->doPaginate($input, 'id') :
            $pager->queryWithoutPaginate($input, 'id');
    }

    public function changeInquirysShow($id)
    {
        $info = GoodsInquirys::where('id', $id)->first();
        if ($info->display_flag == GoodsInquirys::$DISPLAY_FLAG_ON) {
            $displayFlag = GoodsInquirys::$DISPLAY_FLAG_OFF;
        } else if ($info->display_flag == GoodsInquirys::$DISPLAY_FLAG_OFF) {
            $displayFlag = GoodsInquirys::$DISPLAY_FLAG_ON;
        }
        GoodsInquirys::where('id', $id)->update([
            'display_flag' => $displayFlag
        ]);
    }

    public function changeProcess($id)
    {
        GoodsInquirys::where('id', $id)->update([
            'process_status' => GoodsInquirys::$PROCESS_STATUS_FINISH
        ]);
    }

    /**
     * @description:商品基本信息
     * @author     : hkw <hkw925@qq.com>
     * @param     $id      商品id
     * @param int $spec_id 规格id
     * @return array
     */
    public function goodsInfo($id, $spec_id = 0)
    {
        $goods = new Goods();
        $spec  = new GoodsSpecs();
        if ($spec_id) {
            $spec_info = $spec->where('goods_id', $id)->where('id', $spec_id)->first();
        } else {
            $spec_info = $spec->where('goods_id', $id)->first();
        }
        $goods_info = $goods->where('id', $id)->first();
        return [
            'spec_info'  => $spec_info,
            'goods_info' => $goods_info
        ];
    }

    /**
     * @description:添加商品咨询
     * @author     : hkw <hkw925@qq.com>
     * @param $input
     * @return bool
     */
    public function addInquiry($input)
    {
        $goodsInquirys = new GoodsInquirys();
        date_default_timezone_set('PRC');
        $input['inquiry_time'] = date("Y-m-d H:i:s");
        $input['display_flag'] = 1;
        //dd($input);exit;
        return $goodsInquirys->insert($input);
    }

    /**
     * @description:咨询列表
     * @author     : hkw <hkw925@qq.com>
     * @param $goods_id
     * @return \Illuminate\Support\Collection
     */
    public function inquiryList($goods_id)
    {
        $goodsInquirys = new GoodsInquirys();
        return $goodsInquirys->where('goods_id', $goods_id)->orderBy('inquiry_time', 'desc')->get();
    }

    /**
     * @description:商品规格列表
     * @author     : hkw <hkw925@qq.com>
     * @param int    $cate_id
     * @param int    $order_type 排序1价格 2创建时间
     * @param string $keywords
     * @return array
     */
    public function goodsSpecList($cate_id = 0, $order_type = 1, $keywords = '', $input)
    {
        $goodsSpec       = new GoodsSpecs();
        $categoryService = new GoodsCategoryService();
        $goods           = new Goods();
        $goodsSpecEx     = [];
        if ($cate_id) {
            $cate_ids  = $categoryService->getChildId($cate_id);
            $goods_ids = $goods->whereIn('goods_category_id', $cate_ids)->pluck('id');
            $goodsSpec = $goodsSpec->whereIn('goods_id', $goods_ids);
        }
        if ($keywords) {
            $goods_ids   = $goods->where('goods_name', 'like', '%' . $keywords . '%')->pluck('id');
            $goodsSpec   = $goodsSpec->whereIn('goods_id', $goods_ids);
            $goodsSpecEx = $this->goodsSpecListEx($cate_id, $order_type, $keywords);// 模糊查询
            //dd($goodsSpecEx);
            //$goodsSpecEx = @$goodsSpecEx?:[];
            if (!empty($goodsSpecEx)) {
                $goodsSpecEx1    = $goodsSpecEx[0];
                $goodsSpecSingle = $goodsSpecEx[1];
            }
        }
        if ($order_type == 1) {
            $goodsSpec = $goodsSpec->orderBy('price', 'asc');
        } elseif ($order_type) {
            $goodsSpec = $goodsSpec->orderBy('sort_order', 'asc');
        }
        //dd($goods_ids);
        //dd($goodsSpecEx);

        /*if(empty($goodsSpecEx)){
            $res = $goodsSpec->get();
        }else{
            $res = $goodsSpec->union($goodsSpecEx1)->union($goodsSpecSingle)->get();// 精确查找结果集
        }*/
        if (!empty($goodsSpecEx)) {
            $goodsSpec = $goodsSpec->union($goodsSpecEx1)->union($goodsSpecSingle);// 精确查找结果集
        }
        $count  = $goodsSpec->get()->count();
        //dd($count);
        if(isset($input['count']) && $input['count']){
            return ['totalPage'  => $count];
        }
        $offset = ((int)@$input['pageNumber'] - 1) * (int)@$input['pageSize'];
        if ($offset >= $count) {
            $offset = 0;
        }
        $res = $goodsSpec->limit($input['pageSize'])->offset($offset)->get();
        foreach ($res as $k => $v) {
            $res[$k]->goods->goods_name = $v->goods->goods_name;
            $res[$k]->goods->pic = $v->goods->getFullPicturePath();
        }
        //$res[] = @$goodsSpecEx?:[];// 模糊查找结果集
        //dd($res);
        return [
            'totalPage'  => $count,
            'pageNumber' => $input['pageNumber'],
            'list'       => $res
        ]; // 返回精确查找和模糊查找的结果
    }

    /**
     * @description:商品规格列表模糊查询
     * @author     : shuyougeng <13971394623@163.com>
     * @param int    $cate_id
     * @param int    $order_type 排序1价格 2创建时间
     * @param string $keywords
     * @return \Illuminate\Support\Collection
     */
    public function goodsSpecListEx($cate_id = 0, $order_type = 1, $keywords = '')
    {
        $goodsSpec       = new GoodsSpecs();
        $categoryService = new GoodsCategoryService();
        $goods           = new Goods();
        if ($cate_id) {
            $cate_ids  = $categoryService->getChildId($cate_id);
            $goods_ids = $goods->whereIn('goods_category_id', $cate_ids)->pluck('id');
            $goodsSpec = $goodsSpec->whereIn('goods_id', $goods_ids);
        }
        if ($keywords) {
            $goods_ids      = $goods->where('goods_name', 'like', '%' . $keywords . '%')->pluck('id');
            $keywords       = str_replace(' ', '', $keywords);
            $keywords_lenth = mb_strlen($keywords, 'UTF-8');// 获取关键词长度
            $goods_id       = []; // 关键词拆分后 获得的商品ID
            for ($i = 0; $i < $keywords_lenth; $i++) {  // 拆分关键词 变成单个汉字或者字母
                $keyword = mb_substr($keywords, $i, 1, 'utf-8');
                $id_res  = $goods->whereNotIn('id', $goods_ids)->where('goods_name', 'like', '%' . $keyword . '%')->pluck('id');// 排除完全匹配关键词后的产品 使用单字进行查找
                foreach ($id_res as $k => $v) {
                    $goods_id[] = $v;  // 存入商品ID 数组中
                }
            }
            $key_id   = [];
            $id_count = array_count_values($goods_id); // 查找每个id 出现次数
            foreach ($id_count as $k => $v) {
                if ($v == $keywords_lenth) {
                    $key_id[] = $k;  // 当这个id出现次数和关键字长度相同时 称谓完全模糊匹配
                }
            }
            //dd($key_id);
            if (!empty($key_id)) {
                $goodsSpec = $goodsSpec->whereIn('goods_id', $key_id);
            } else {
                $goodsSpec = $goodsSpec->where('goods_id', 0);
            }
            //dd($goodsSpec);
            $goodsSpecSingle = $this->goodsSpecListSingle($cate_id, $order_type, $goods_id, $key_id);
        }
        if ($order_type == 1) {
            $goodsSpec = $goodsSpec->orderBy('price', 'asc');
        } elseif ($order_type) {
            $goodsSpec = $goodsSpec->orderBy('sort_order', 'asc');
        }
        $res[] = $goodsSpec;
        $res[] = $goodsSpecSingle;
        //dd($res);
        return $res;
    }


    /**
     * @description:商品规格列表模糊查询
     * @author     : shuyougeng <13971394623@163.com>
     * @param int   $cate_id
     * @param int   $order_type 排序1价格 2创建时间
     * @param array $goods_id   模糊查询得出的goods_id
     * @param array $key_id     模糊查询 全匹配的goods_id
     * @return \Illuminate\Support\Collection
     */
    public function goodsSpecListSingle($cate_id = 0, $order_type = 1, $goods_id = '', $key_id = '')
    {
        $goodsSpec       = new GoodsSpecs();
        $categoryService = new GoodsCategoryService();
        $goods           = new Goods();
        if ($cate_id) {
            $cate_ids  = $categoryService->getChildId($cate_id);
            $goods_ids = $goods->whereIn('goods_category_id', $cate_ids)->pluck('id');
            $goodsSpec = $goodsSpec->whereIn('goods_id', $goods_ids);
        }
        if (!empty($goods_id)) {
            if ($goods_id != $key_id) { //数组不为空 查询匹配的商品
                $goodsSpec = $goodsSpec->whereNotIn('goods_id', $key_id)->whereIn('goods_id', $goods_id);
            } else { // 数组为空  查询结果集为空
                $goodsSpec = $goodsSpec->where('goods_id', 0);
            }
        } else {
            $goodsSpec = $goodsSpec->where('goods_id', 0);
        }
        if ($order_type == 1) {
            $goodsSpec = $goodsSpec->orderBy('price', 'asc');
        } elseif ($order_type) {
            $goodsSpec = $goodsSpec->orderBy('sort_order', 'asc');
        }
        //dd($goodsSpec->get());
        return $goodsSpec;
    }

    public function specList(Array $input)
    {
        $model           = new GoodsSpecs();
        $categoryService = new GoodsCategoryService();
        $cate_id_array   = $categoryService->getChildId($input['cate_id']);
        $goods_ids       = Goods::whereIn('goods_category_id', $cate_id_array)->pluck('id');
        $model           = $model->whereIn('goods_id', $goods_ids);
        $pager           = new QueryPager($model);
        $pager->setRefectionMethodField('getGoods');
        $pager->setRefectionMethodField('goodsPic');
        return $pager->doPaginate1($input, 'sort_order');
    }

    public function specListSearch(Array $input)
    {
        $goods      = new Goods();
        $pageNumber = $input["pageNumber"];
        $pageSzie   = $input["pageSize"];
        $keywords   = $input["keywords"];
        $spec       = $this->goodsSpecList(0, 1, $keywords)->toArray();
        //dd($spec);
        $res = array_splice($spec, ($pageNumber - 1) * $pageSzie, $pageSzie);
        foreach ($res as $k => $v) {
            $res[$k]['getGoods'] = $goods->where('id', $v['goods_id'])->first();
            $res[$k]['goodsPic'] = $res[$k]['getGoods']->goods_picture;
        }
        //dump($res);
        $totalPage = ceil(count($spec) / $pageSzie);
        $list      = [
            'totalPage' => $totalPage,
            'pageSize'  => $pageSzie,
            'list'      => $res,
            'keywords'  => $keywords,
        ];
        return $list;
    }

    public function goodsBatchAdd(Array $input)
    {
        $fullFilePath = storage_path('app/exportexcel') . '/' . $input['load_file_name'];
        $error        = [];
        Excel::load($fullFilePath, function ($reader) use ($input, &$error) {
            $initData    = $reader->ignoreEmpty()->limitColumns(14)->limit(false, 1)->get();
            $otherData   = $reader->ignoreEmpty()->limitColumns(false, 14)->limit(false)->get();
            $dealData    = $otherData->toArray();
            $newDealData = [];
            if (!empty($dealData)) {
                foreach ($dealData as $k0 => $v0) {
                    $v0 = array_filter($v0);

                    if ($k0 == 0 || empty($v0)) {
                        continue;
                    }
                    foreach ($dealData[0] as $k => $v) {
                        if (!$v) {
                            continue;
                        }
                        $newDealData[$k0 - 1][$v] = $v0[$k];
                    }
                }
            }
            foreach ($initData as $k => $v) {
                $data1 = array_filter($v->toArray());
                if (empty($data1)) {
                    continue;
                }
                $data      = array_values($v->toArray());
                $dataOther = [];
                if (!empty($newDealData)) {
                    $dataOther = $newDealData[$k];
                }
                $res = $this->addGoodsByBatch($data, $dataOther, $input);
                if (isset($res['code']) && $res['code'] == 1) {
                    $error[]['goods_name'] = $data[0];
                    continue;
                }
            }
        }, 'UTF-8');
        unlink($fullFilePath);
        return $error;
    }

    public function contentReplace($data, $txt)
    {
        $content = str_replace('${A}', $data[0], $txt);
        $content = str_replace('${B}', $data[1], $content);
        $content = str_replace('${C}', $data[2], $content);
        $content = str_replace('${D}', $data[3], $content);
        $content = str_replace('${E}', $data[4], $content);
        $content = str_replace('${F}', $data[5], $content);
        $content = str_replace('${G}', $data[6], $content);
        $content = str_replace('${H}', $data[7], $content);
        $content = str_replace('${I}', $data[8], $content);
        $content = str_replace('${J}', $data[9], $content);
        $content = str_replace('${K}', $data[10], $content);
        $content = str_replace('${L}', $data[11], $content);
        return $content;
    }

    public function addGoodsByBatch($data, $dataOther, $input)
    {
        $fileNameArr = explode('/', $data[5]);
        $fileIds     = [];
        foreach ($fileNameArr as $k => $v) {
            $fileIds[] = ServiceFiles::where('name', 'like', '%' . $v . '%')->value('id');
        }
        $fileIds = array_filter($fileIds);
        if (count($fileIds) != count($fileNameArr)) {
            return ['code' => 1];
        }
//        $fileId = ServiceFiles::where('name', 'like', '%' . $data[4] . '%')->value('id');
//        if (!$fileId) {
//            return ['code' => 1];
//        }
        $data[13] = nl2br($data[13]);// 商品详情换行替换
        DB::transaction(function () use ($data, $input, $dataOther, $fileIds) {
            // 批量导入的EXCEL中 找到 商品分类
            if ($data[1]) {
                // << 分隔符将批量导入的分类进行拆分
                $cate                 = explode('>>', $data[1]);
                $goodsCategory        = new GoodsCategory();
                $goodsCategoryService = new GoodsCategoryService();
                $leafCate             = $goodsCategory->pluck('goods_name')->toArray();
                // 遍历批量上传得到的商品分类
                foreach ($cate as $k => $v) {
                    if (!in_array($v, $leafCate)) {  // 当商品分类不在无限极分类中时
                        if ($k == 0) { // 第一级就不是 直接分配到 蓝图科技分类下
                            $goods = GoodsCategory::create([
                                'goods_name' => $v,
                                'sort_order' => 10,
                                'parent_id'  => 1,
                            ]);
                        } else { // 当第二级开始不在无限极分类 通过上一级找到 parent_id  再存入goods_category 中
                            $parent_id = $goodsCategoryService->getCateId($cate[$k - 1])['id'];
                            $goods     = GoodsCategory::create([
                                'goods_name' => $v,
                                'sort_order' => 10,
                                'parent_id'  => $parent_id,
                            ]);
                        }
                    }
                }
                // 当批量插入带有分类时获得其分类id
                $goods_category_id = $goodsCategoryService->getCateId(end($cate))['id'];
            }
            $goodsInfo               = Goods::create([
                'goods_name'        => $data[0],
                'goods_vendor'      => $data[2],
                'sort_order'        => $data[3],
                'list_flag'         => $data[4] == '是' ? 1 : 2,
                'goods_category_id' => $goods_category_id ? $goods_category_id : $input['goods_category_id'],
                'goods_picture'     => $input['goods_picture'],
                'goods_content'     => $data[13]
            ]);
            $goodsInfo->goods_qrcode = $this->goodsQRCode($goodsInfo->id);
            $goodsInfo->save();
            $goodsSpecData = [];
            $maxCount      = 0;
            for ($i = 6; $i < 12; $i++) {
                $data[$i] = explode('/', $data[$i]);
                if (count($data[$i]) > $maxCount) {
                    $maxCount = count($data[$i]);
                }
            }
            for ($j = 0; $j < $maxCount; $j++) {
                $goodsSpecData[$j]['goods_spec']      = @$data[6][$j] ?: $data[6][0];
                $goodsSpecData[$j]['goods_number']    = @$data[7][$j] ?: $data[7][0];
                $goodsSpecData[$j]['inventory']       = @$data[8][$j] ?: $data[8][0];
                $goodsSpecData[$j]['price']           = @$data[9][$j] ?: $data[9][0];
                $goodsSpecData[$j]['unit']            = @$data[10][$j] ?: $data[10][0];
                $goodsSpecData[$j]['min_buy_amount']  = @$data[11][$j] ?: $data[11][0];
                $goodsSpecData[$j]['sort_order']      = @$data[12][$j] ?: $data[12][0];
                $goodsSpecData[$j]['goods_id']        = $goodsInfo->id;
                $goodsSpecData[$j]['display_flag']    = 1;
                $goodsSpecData[$j]['goods_spec_pic1'] = $input['goods_spec_pic1'];
                $goodsSpecData[$j]['goods_spec_pic2'] = $input['goods_spec_pic2'];
                $goodsSpecData[$j]['goods_spec_pic3'] = $input['goods_spec_pic3'];
            }
            GoodsSpecs::insert($goodsSpecData);

//            GoodsSpecs::create([
//                'goods_spec'     => $data[5],
//                'goods_number'   => $data[6],
//                'inventory'      => $data[7],
//                'price'          => $data[8],
//                'unit'           => $data[9],
//                'min_buy_amount' => $data[10],
//                'sort_order'     => $data[11],
//                'goods_id'       => $goodsInfo->id,
//                'display_flag'   => 1,
//                'goods_spec_pic1'=>$input['goods_spec_pic1'],
//                'goods_spec_pic2'=>$input['goods_spec_pic2'],
//                'goods_spec_pic3'=>$input['goods_spec_pic3'],
//            ]);

            $param = [];
            foreach ($dataOther as $k => $v) {
                if (!$v) {
                    continue;
                }
                $param[$k]['params_name']  = $k;
                $param[$k]['params_value'] = $v;
                $param[$k]['goods_id']     = $goodsInfo->id;
            }
            GoodsParams::insert($param);
            foreach ($fileIds as $v) {
                GoodsFiles::create([
                    'file_id'  => $v,
                    'goods_id' => $goodsInfo->id
                ]);
            }
//            GoodsFiles::create([
//                'file_id'  => $fileId,
//                'goods_id' => $goodsInfo->id
//            ]);
        });
    }

    public function goodsSpecBatchEdit(Array $input)
    {
        //dd($input);
        // 获取待编辑的商品id
        $goods_ids = $input['goods_ids'];
        $goods_ids = explode('/', $goods_ids);
        // 处理传入的编辑内容
        // 商品分类
        $cate_id = $input['goods_category'];
        if ($cate_id != 0) {
            $goods = new Goods();
            $res   = $goods->whereIn('id', $goods_ids)->update(['goods_category_id' => $cate_id]);
            if (!$res) {
                return ['code' => 1];
            }
        }
        // 判断需编辑的规格的字段映射
        $map = [];
        // 规格名修改
        $spec = $input['goods_spec'];
        if (!empty($spec)) {
            $map['goods_spec'] = $spec;
        }
        // 货号修改
        $num = $input['goods_number'];
        if (!empty($num)) {
            $map['goods_number'] = $num;
        }
        // 库存修改
        $inventory = $input['inventory'];
        if (!empty($inventory)) {
            $map['inventory'] = $inventory;
        }
        // 价格修改
        $price = $input['price'];
        if (!empty($price)) {
            $map['price'] = $price;
        }
        // 原始价格修改
        $origin_price = $input['origin_price'];
        if (!empty($origin_price)) {
            $map['origin_price'] = $origin_price;
        }
        // 进货价格修改
        $cost_price = $input['cost_price'];
        if (!empty($cost_price)) {
            $map['cost_price'] = $cost_price;
        }
        // 销售单位修改
        $unit = $input['unit'];
        if (!empty($unit)) {
            $map['unit'] = $unit;
        }
        // 最小购货数修改
        $min_buy_amount = $input['min_buy_amount'];
        if (!empty($min_buy_amount)) {
            $map['min_buy_amount'] = $min_buy_amount;
        }
        // 排序修改
        $sort_order = $input['sort_order'];
        if (!empty($sort_order)) {
            $map['sort_order'] = $sort_order;
        }
        // 货期修改
        $delivery_time = $input['delivery_time'];
        if ($delivery_time != 0) {
            $map['delivery_time'] = $delivery_time;
        }
        // 是否上架
        $display_flag = $input['display_flag'];
        if ($display_flag != 0) {
            $map['display_flag'] = $display_flag;
        }
        // 橱窗图片1
        $goods_spec_pic1 = $input['goods_spec_pic1'];
        if (!empty($goods_spec_pic1)) {
            $map['goods_spec_pic1'] = $goods_spec_pic1;
        }
        // 橱窗图片2
        $goods_spec_pic2 = $input['goods_spec_pic2'];
        if (!empty($goods_spec_pic2)) {
            $map['goods_spec_pic2'] = $goods_spec_pic2;
        }
        // 橱窗图片3
        $goods_spec_pic3 = $input['goods_spec_pic3'];
        if (!empty($goods_spec_pic3)) {
            $map['goods_spec_pic3'] = $goods_spec_pic3;
        }
        // 橱窗图片4
        $goods_spec_pic4 = $input['goods_spec_pic4'];
        if (!empty($goods_spec_pic4)) {
            $map['goods_spec_pic4'] = $goods_spec_pic4;
        }
        // 橱窗图片5
        $goods_spec_pic5 = $input['goods_spec_pic5'];
        if (!empty($goods_spec_pic5)) {
            $map['goods_spec_pic5'] = $goods_spec_pic5;
        }
        $goods_spec = new GoodsSpecs();
        $update_res = $goods_spec->whereIn('goods_id', $goods_ids)->update($map);
        if (!$update_res) {
            return ['code' => 1];
        }
    }
}

